const inquirer = require('inquirer')
const fs = require('fs')
const { resolve, exit } = require('./index')

module.exports = function(selectMsg) {
  const configData = require(resolve('micro-config'))

  /* 获取入口配置 */
  let entryData

  try {
    /* 遍历entry文件夹，子目录的名为入口value值，再读取其中config.json文件的name和 */
    const dirs = fs.readdirSync(resolve('src/entry'))
    const ports = {}

    entryData = dirs.map(dirname => {
      const config = require(resolve(`src/entry/${ dirname }/config.json`))

      /* 判空 */
      if (!config) {
        throw new Error(`${ dirname }配置文件不存在!`)
      }
      /* 端口是否重复 */
      if (ports[ config.port ]) {
        throw new Error(`${ dirname }与${ ports[ config.port ] }端口配置相同,请修改`)
      } else {
        ports[ config.port ] = dirname
      }

      return {
        name: config.name || '未命名',
        port: config.port || 4000,
        entry: dirname,
        checked: config.checked === true,
        distPath: `${ configData.distPath }${ dirname }`
      }
    })

  } catch (err) {
    exit(err)
  }

  return inquirer.prompt([{
    type: 'checkbox',
    name: 'entry',
    message: selectMsg,
    choices: entryData
  }])
    .then(res => entryData.filter(item => res.entry.indexOf(item.name) > -1))
}
